import os
import sys
import subprocess

def convert_epub_to_pdf(epub_path, output_dir):
    """
    将单个 .epub 文件转换为 .pdf 文件
    """
    pdf_filename = os.path.splitext(os.path.basename(epub_path))[0] + '.pdf'
    pdf_path = os.path.join(output_dir, pdf_filename)
    try:
        subprocess.run(['ebook-convert', epub_path, pdf_path], check=True)
        print(f"转换成功: {pdf_path}")
    except subprocess.CalledProcessError as e:
        print(f"转换失败: {epub_path}")

def process_files_or_folders(paths):
    """
    处理拖放的文件或文件夹
    """
    for path in paths:
        if os.path.isfile(path) and path.lower().endswith('.epub'):
            # 如果是 .epub 文件，直接转换
            convert_epub_to_pdf(path, os.path.dirname(path))
        elif os.path.isdir(path):
            # 如果是文件夹，遍历文件夹中的所有 .epub 文件
            for root, _, files in os.walk(path):
                for filename in files:
                    if filename.lower().endswith('.epub'):
                        epub_path = os.path.join(root, filename)
                        convert_epub_to_pdf(epub_path, root)
        else:
            print(f"跳过无效路径: {path}")

if __name__ == "__main__":
    if len(sys.argv) > 1:
        # 获取拖放的文件或文件夹路径
        paths = sys.argv[1:]
        process_files_or_folders(paths)
    else:
        print("请将文件或文件夹拖放到此程序上进行转换。")
